package com.zy.orders.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.model.OrderItems;
import com.zy.model.Orders;
import com.zy.orders.mapper.OrdersMapper;
import com.zy.web.api.IdGeneratorApi;
import com.zy.web.bean.OrdersDTO;
import com.zy.web.bean.OrdersItemsDTO;
import com.zy.web.bean.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private IdGeneratorApi idGeneratorApi;

    // 假设你有一个 OrderItemsService 用于操作订单项
     @Autowired
     private OrdersItemsService ordersItemsService;
     @Autowired
     private CartService cartService;



    @Override
    @Transactional
    public OrdersDTO createOrder(Long userId, OrdersDTO ordersDTO, List<OrdersItemsDTO> orderItemsDTOList, List<Long> cartIds) {
        ResponseResult rr = idGeneratorApi.getNextId();
        if( rr.getCode()==0){
            throw new RuntimeException("获取id失败");
        }
        // 关键改动：将返回的数据强转为 List<Long> 类型
       Long orderId=Long.parseLong( rr.getData().toString() );


        // 2. 将 DTO 转换为实体类，并设置新生成的ID和时间
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDTO, orders);
        orders.setId(orderId);
        orders.setOrderStatus(1); // 默认设置为待支付
        orders.setUpdateTime(LocalDateTime.now());
        orders.setUserId(userId);
        // 3. 插入订单主表
        this.save(orders);
        // 4. 处理订单项列表
        if (orderItemsDTOList != null && !orderItemsDTOList.isEmpty()) {
            List<OrderItems> orderItemsList = orderItemsDTOList.stream()
                    .map(itemDTO -> {
                        OrderItems orderItem = new OrderItems();
                        BeanUtils.copyProperties(itemDTO, orderItem);
                        orderItem.setOrderId(orderId);
                        return orderItem;
                    })
                    .collect(Collectors.toList());

            // 调用 OrderItemsService 进行批量插入
            ordersItemsService.saveBatchOrderItems(orderItemsList);
        }

        // 5. 还要删除  cart购物车表中的当前userId的这些被购买的商品的记录
        cartIds.stream().map(cartId -> cartService.deleteCartItem(userId,cartId)).collect(Collectors.toList());


        BeanUtils.copyProperties(  orders, ordersDTO);
        return ordersDTO;
    }
}
